package com.momo.mal.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.momo.mal.entity.Anime;
import com.momo.mal.entity.History;
import com.momo.mal.entity.Manga;
import com.momo.mal.entity.Related;
import com.momo.mal.util.ConnectionUtil;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;

public class MalDatabaseAdapter {
	private Context context;
	private Uri dbUriAnime = Uri
			.parse(MalDatabaseContentProvider.CONTENT_PATH
					+ MalDatabaseContentProvider.TABLES[0]);
	private Uri dbUriManga = Uri
			.parse(MalDatabaseContentProvider.CONTENT_PATH
					+ MalDatabaseContentProvider.TABLES[1]);
	private Uri dbUriStatistic = Uri
			.parse(MalDatabaseContentProvider.CONTENT_PATH
					+ MalDatabaseContentProvider.TABLES[2]);
	private Uri dbUriHistory = Uri
			.parse(MalDatabaseContentProvider.CONTENT_PATH
					+ MalDatabaseContentProvider.TABLES[3]);
	private Uri dbUriRelated = Uri
			.parse(MalDatabaseContentProvider.CONTENT_PATH
					+ MalDatabaseContentProvider.TABLES[4]);

	public MalDatabaseAdapter(Context context) {
		this.context = context;
	}
	
	public void updateAnimePriority() {
		ContentValues contentValues = new ContentValues();
		contentValues.put(AnimeColumn.PRIORITY, "2");
		
		context.getContentResolver().update(dbUriAnime, contentValues, null, null);
	}
	
	public void updateMangaPriority() {
		ContentValues contentValues = new ContentValues();
		contentValues.put(MangaColumn.PRIORITY, "0");
		
		context.getContentResolver().update(dbUriManga, contentValues, null, null);
	}
	
	public void deleteAllAnime() {
		context.getContentResolver().delete(dbUriAnime, null, null);
	}
	
	public void deleteAllManga() {
		context.getContentResolver().delete(dbUriManga, null, null);
	}
	
	public boolean isAnimeDataExist() {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, null, null, null);
		if(cursor.getCount() != 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
		
	}
	
	public boolean isMangaDataExist() {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, null, null, null);
		if(cursor.getCount() != 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}
	
	public boolean hasAnime(String id) {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, AnimeColumn.ID + " = ?", new String[] {id}, null);
		if(cursor.getCount() != 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}
	
	public boolean hasManga(String id) {
		Cursor cursor = context.getContentResolver().query(dbUriManga, null, MangaColumn.ID + " = ?", new String[] {id}, null);
		if(cursor.getCount() != 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
		
	}
	
	public boolean isAnimeSyncronized(int count) {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, null, null, null);
		if(cursor.getCount() == count) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
		
	}
	
	public boolean isMangaSyncronized(int count) {
		Cursor cursor = context.getContentResolver().query(dbUriManga, null, null, null, null);
		if(cursor.getCount() == count) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
		
	}
	
	public int countAnimeByStatus(String status) {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, AnimeColumn.WATCHED_STATUS + " = ?", new String[] {status}, null);
		int count = cursor.getCount();
		
		cursor.close();
		
		return count;
	}
	
	public int countMangaByStatus(String status) {
		Cursor cursor = context.getContentResolver().query(dbUriManga, null, MangaColumn.READ_STATUS + " = ?", new String[] {status}, null);
		int count = cursor.getCount();
		
		cursor.close();
		
		return count;
	}
	
	public int countAnime() {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, null, null, null);
		int count = cursor.getCount();
		
		cursor.close();
		
		return count;
	}
	
	public int countManga() {
		Cursor cursor = context.getContentResolver().query(dbUriManga, null, null, null, null);
		int count = cursor.getCount();
		
		cursor.close();
		
		return count;
	}
	
	public List<String> getAllAnime() {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, null, null, null);
		
		List<String> animes = new ArrayList<String>();
		if(cursor != null) {
			while(cursor.moveToNext()) {
				animes.add(cursor.getString(cursor.getColumnIndex(AnimeColumn.ID)));
			}
		}
		
		cursor.close();
		
		return animes;
	}
	
	public List<String> getAllManga() {
		Cursor cursor = context.getContentResolver().query(dbUriManga, null, null, null, null);
		
		List<String> mangas = new ArrayList<String>();
		if(cursor != null) {
			while(cursor.moveToNext()) {
				mangas.add(cursor.getString(cursor.getColumnIndex(MangaColumn.ID)));
			}
		}
		
		cursor.close();
		
		return mangas;
	}
	
	public String[] getStatistic() {
		Cursor cursor = context.getContentResolver().query(dbUriStatistic, null, null, null, null);
		cursor.moveToFirst();
		String[] data = new String[2];
		data[0] = cursor.getString(cursor.getColumnIndex("anime_days"));
		data[1] = cursor.getString(cursor.getColumnIndex("manga_days"));
		
		cursor.close();
		
		return data;
	}
	
	public void deleteAnime(String id) {
		context.getContentResolver().delete(dbUriAnime, AnimeColumn.ID + " = ?", new String[] {id});
	}
	
	public void deleteManga(String id) {
		context.getContentResolver().delete(dbUriManga, MangaColumn.ID + " = ?", new String[] {id});
	}
	
	public void saveStatistic(String[] data) {
		context.getContentResolver().delete(dbUriStatistic, null, null);
		
		ContentValues contentValues = new ContentValues();
		contentValues.put("anime_days", data[0]);
		contentValues.put("manga_days", data[1]);
		
		context.getContentResolver().insert(dbUriStatistic, contentValues);
	}
	
	public boolean isAnimeSync(String id) {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, AnimeColumn.ID + " = ?", new String[] {id}, null);
		cursor.moveToFirst();
		String statusSync = cursor.getString(cursor.getColumnIndex(AnimeColumn.STATUS_SYNC));
		cursor.close();
		if(statusSync.equalsIgnoreCase("sync")) {
			return true;
		} else {
			return false;
		}
		
	}
	
	public boolean isMangaSync(String id) {
		Cursor cursor = context.getContentResolver().query(dbUriManga, null, MangaColumn.ID + " = ?", new String[] {id}, null);
		cursor.moveToFirst();
		String statusSync = cursor.getString(cursor.getColumnIndex(MangaColumn.STATUS_SYNC));
		cursor.close();
		if(statusSync.equalsIgnoreCase("sync")) {
			return true;
		} else {
			return false;
		}
		
	}
	
	public Anime getAnimeById(String id) {
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null, AnimeColumn.ID + " = ?", new String[] {id}, null);
		
		Anime anime = new Anime();
		if(cursor != null) {
			if(cursor.getCount() != 0) {
				anime = new Anime();
				cursor.moveToFirst();
				anime.setId(cursor.getString(cursor.getColumnIndex(AnimeColumn.ID)));
				anime.setTitle(cursor.getString(cursor.getColumnIndex(AnimeColumn.TITLE)));
				anime.setType(cursor.getString(cursor.getColumnIndex(AnimeColumn.TYPE)));
				anime.setStatus(cursor.getString(cursor.getColumnIndex(AnimeColumn.STATUS)));
				anime.setEpisode(cursor.getString(cursor.getColumnIndex(AnimeColumn.EPISODE)));
				anime.setClassification(cursor.getString(cursor.getColumnIndex(AnimeColumn.CLASSIFICATION)));
				anime.setSynopsis(cursor.getString(cursor.getColumnIndex(AnimeColumn.SYSNOPSIS)));
		
				anime.setMemberScore(cursor.getString(cursor.getColumnIndex(AnimeColumn.MEMBER_SCORE)));
				anime.setRank(cursor.getString(cursor.getColumnIndex(AnimeColumn.RANK)));
				anime.setPopularityRank(cursor.getString(cursor.getColumnIndex(AnimeColumn.POPULARITY_RANK)));
				anime.setMemberCount(cursor.getString(cursor.getColumnIndex(AnimeColumn.MEMBER_COUNT)));
				anime.setFavoriteCount(cursor.getString(cursor.getColumnIndex(AnimeColumn.FAVORITE_COUNT)));
				
				anime.setGenre(cursor.getString(cursor.getColumnIndex(AnimeColumn.GENRE)));
				anime.setWatchedEpisode(cursor.getString(cursor.getColumnIndex(AnimeColumn.WATCHED_EPISODE)));
				anime.setWathcedStatus(cursor.getString(cursor.getColumnIndex(AnimeColumn.WATCHED_STATUS)));
				anime.setScore(cursor.getString(cursor.getColumnIndex(AnimeColumn.SCORE)));
				
				anime.setEnglish(cursor.getString(cursor.getColumnIndex(AnimeColumn.ENGLISH)));
				anime.setSynonyms(cursor.getString(cursor.getColumnIndex(AnimeColumn.SYNONYMS)));
				anime.setJapanese(cursor.getString(cursor.getColumnIndex(AnimeColumn.JAPANESE)));
				
				anime.setAdaptation(cursor.getString(cursor.getColumnIndex(AnimeColumn.ADAPTATION)));
				anime.setPrequel(cursor.getString(cursor.getColumnIndex(AnimeColumn.PREQUEL)));
				anime.setSequel(cursor.getString(cursor.getColumnIndex(AnimeColumn.SEQUEL)));
				anime.setSideStory(cursor.getString(cursor.getColumnIndex(AnimeColumn.SIDE_STORY)));
				anime.setSpinOff(cursor.getString(cursor.getColumnIndex(AnimeColumn.SPIN_OFF)));
				anime.setAlternative(cursor.getString(cursor.getColumnIndex(AnimeColumn.ALTERNATIVE)));
				
				anime.setStatusSync(cursor.getString(cursor.getColumnIndex(AnimeColumn.STATUS_SYNC)));
				anime.setTags(cursor.getString(cursor.getColumnIndex(AnimeColumn.TAGS)));
				anime.setComments(cursor.getString(cursor.getColumnIndex(AnimeColumn.COMMENTS)));
				anime.setStartDate(cursor.getString(cursor.getColumnIndex(AnimeColumn.START_DATE)));
				anime.setEndDate(cursor.getString(cursor.getColumnIndex(AnimeColumn.END_DATE)));
				anime.setImageUrl(cursor.getString(cursor.getColumnIndex(AnimeColumn.IMAGE_URL)));
				anime.setPriority(cursor.getString(cursor.getColumnIndex(AnimeColumn.PRIORITY)));
				
				anime.setRelations(getRelatedAnime(cursor.getString(cursor.getColumnIndex(AnimeColumn.ID))));
				
			}
		}
		cursor.close();
		
		return anime;
	}
	
	public List<Related> getRelatedAnime(String id) {
		Cursor cursor = context.getContentResolver().query(dbUriRelated, null, RelatedColumn.MASTER_ID + " = ? AND " + RelatedColumn.IS_ANIME + " = 1", new String[] {id}, null);
		List<Related> relations = new ArrayList<Related>();
		if(cursor != null) {
			while(cursor.moveToNext()) {
				Related related = new Related();
				related.setAnime(cursor.getInt(cursor.getColumnIndex(RelatedColumn.IS_ANIME)));
				related.setMasterId(cursor.getString(cursor.getColumnIndex(RelatedColumn.MASTER_ID)));
				related.setRelatedId(cursor.getString(cursor.getColumnIndex(RelatedColumn.RELATED_ID)));
				related.setTitle(cursor.getString(cursor.getColumnIndex(RelatedColumn.TITLE)));
				related.setType(cursor.getString(cursor.getColumnIndex(RelatedColumn.TYPE)));
				relations.add(related);
			}
		}
		
		cursor.close();
		
		return relations;
	}
	
	public Manga getMangaById(String id) {
		Cursor cursor = context.getContentResolver().query(dbUriManga, null, AnimeColumn.ID + " = ?", new String[] {id}, null);
		
		Manga manga = null;
		if(cursor != null) {
			if(cursor.getCount() != 0) {
				manga = new Manga();
				cursor.moveToFirst();
				manga.setId(cursor.getString(cursor.getColumnIndex(MangaColumn.ID)));
				manga.setChapterRead(cursor.getString(cursor.getColumnIndex(MangaColumn.CHAPTER_READ)));
				manga.setChapters(cursor.getString(cursor.getColumnIndex(MangaColumn.CHAPTERS)));
				manga.setFavoriteCount(cursor.getString(cursor.getColumnIndex(MangaColumn.FAVORITE_COUNT)));
				manga.setGenres(cursor.getString(cursor.getColumnIndex(MangaColumn.GENRES)));
				manga.setId(cursor.getString(cursor.getColumnIndex(MangaColumn.ID)));
				manga.setImageUrl(cursor.getString(cursor.getColumnIndex(MangaColumn.IMAGE_URL)));
				manga.setListedMangaId(cursor.getString(cursor.getColumnIndex(MangaColumn.LISTED_MANGA)));
				manga.setMemberCount(cursor.getString(cursor.getColumnIndex(MangaColumn.MEMBER_COUNT)));
				manga.setMemberScore(cursor.getString(cursor.getColumnIndex(MangaColumn.MEMBER_SCORE)));
				manga.setPopularityRank(cursor.getString(cursor.getColumnIndex(MangaColumn.POPULARITY_RANK)));
				manga.setRank(cursor.getString(cursor.getColumnIndex(MangaColumn.RANK)));
				manga.setReadStatus(cursor.getString(cursor.getColumnIndex(MangaColumn.READ_STATUS)));
				manga.setScore(cursor.getString(cursor.getColumnIndex(MangaColumn.SCORE)));
				manga.setStatus(cursor.getString(cursor.getColumnIndex(MangaColumn.STATUS)));
				manga.setSynopsis(cursor.getString(cursor.getColumnIndex(MangaColumn.SYNOPSIS)));
				manga.setTags(cursor.getString(cursor.getColumnIndex(MangaColumn.TAGS)));
				manga.setTitle(cursor.getString(cursor.getColumnIndex(MangaColumn.TITLE)));
				manga.setType(cursor.getString(cursor.getColumnIndex(MangaColumn.TYPE)));
				manga.setVolumes(cursor.getString(cursor.getColumnIndex(MangaColumn.VOLUMES)));
				manga.setVolumesRead(cursor.getString(cursor.getColumnIndex(MangaColumn.VOLUME_READ)));
				manga.setEnglish(cursor.getString(cursor.getColumnIndex(MangaColumn.ENGLISH)));
				manga.setJapanese(cursor.getString(cursor.getColumnIndex(MangaColumn.JAPANESE)));
				manga.setSynonyms(cursor.getString(cursor.getColumnIndex(MangaColumn.SYNONYM)));
				manga.setRelatedManga(cursor.getString(cursor.getColumnIndex(MangaColumn.RELATED_MANGA)));
				manga.setAlternative(cursor.getString(cursor.getColumnIndex(MangaColumn.ALTERNATIVE_VERSION)));
				manga.setListedMangaId(cursor.getString(cursor.getColumnIndex(MangaColumn.LISTED_MANGA)));
				manga.setAnimeAdaptation(cursor.getString(cursor.getColumnIndex(MangaColumn.ANIME_ADAPTATION)));
				manga.setStartDate(cursor.getString(cursor.getColumnIndex(MangaColumn.START_DATE)));
				manga.setEndDate(cursor.getString(cursor.getColumnIndex(MangaColumn.END_DATE)));
				manga.setComments(cursor.getString(cursor.getColumnIndex(MangaColumn.COMMENTS)));
				manga.setPriority(cursor.getString(cursor.getColumnIndex(MangaColumn.PRIORITY)));
				manga.setStatusSync(cursor.getString(cursor.getColumnIndex(MangaColumn.STATUS_SYNC)));
				
				manga.setRelated(getRelatedManga(cursor.getString(cursor.getColumnIndex(MangaColumn.ID))));
			}
		}
		cursor.close();
		
		return manga;
	}
	
	public List<Related> getRelatedManga(String id) {
		Cursor cursor = context.getContentResolver().query(dbUriRelated, null, RelatedColumn.MASTER_ID + " = ? AND " + RelatedColumn.IS_ANIME + " = 0", new String[] {id}, null);
		List<Related> relations = new ArrayList<Related>();
		if(cursor != null) {
			while(cursor.moveToNext()) {
				Related related = new Related();
				related.setAnime(cursor.getInt(cursor.getColumnIndex(RelatedColumn.IS_ANIME)));
				related.setMasterId(cursor.getString(cursor.getColumnIndex(RelatedColumn.MASTER_ID)));
				related.setRelatedId(cursor.getString(cursor.getColumnIndex(RelatedColumn.RELATED_ID)));
				related.setTitle(cursor.getString(cursor.getColumnIndex(RelatedColumn.TITLE)));
				related.setType(cursor.getString(cursor.getColumnIndex(RelatedColumn.TYPE)));
				relations.add(related);
			}
		}
		
		cursor.close();
		
		return relations;
	}
	
	public void updateAnimeSync(Anime anime) {
		ContentValues contentValuesAnime = new ContentValues();
		
		contentValuesAnime.put(AnimeColumn.ENGLISH, anime.getEnglish());
		contentValuesAnime.put(AnimeColumn.JAPANESE, anime.getJapanese());
		contentValuesAnime.put(AnimeColumn.SYNONYMS, anime.getSynonyms());
		contentValuesAnime.put(AnimeColumn.SYSNOPSIS, anime.getSynopsis());
		contentValuesAnime.put(AnimeColumn.RANK, anime.getRank());
		
		contentValuesAnime.put(AnimeColumn.POPULARITY_RANK, anime.getPopularityRank());
		contentValuesAnime.put(AnimeColumn.STATUS, anime.getStatus());
		contentValuesAnime.put(AnimeColumn.GENRE, anime.getGenre());
		contentValuesAnime.put(AnimeColumn.CLASSIFICATION, anime.getClassification());
		contentValuesAnime.put(AnimeColumn.MEMBER_SCORE, anime.getMemberScore());
		
		contentValuesAnime.put(AnimeColumn.MEMBER_COUNT, anime.getMemberCount());
		contentValuesAnime.put(AnimeColumn.FAVORITE_COUNT, anime.getFavoriteCount());
		contentValuesAnime.put(AnimeColumn.PARENT_STORY, anime.getParentStory());
		contentValuesAnime.put(AnimeColumn.LISTED_ANIME_ID, anime.getListedAnimeId());
		contentValuesAnime.put(AnimeColumn.ADAPTATION, anime.getAdaptation());
		
		contentValuesAnime.put(AnimeColumn.SIDE_STORY, anime.getSideStory());
		contentValuesAnime.put(AnimeColumn.PREQUEL, anime.getPrequel());
		contentValuesAnime.put(AnimeColumn.SEQUEL, anime.getSequel());
		contentValuesAnime.put(AnimeColumn.ALTERNATIVE, anime.getAlternative());
		contentValuesAnime.put(AnimeColumn.SPIN_OFF, anime.getSpinOff());
		contentValuesAnime.put(AnimeColumn.STATUS_SYNC, "sync");
		
		context.getContentResolver().update(dbUriAnime, contentValuesAnime, AnimeColumn.ID + " = ?", new String[] {anime.getId()});
		
		saveCache("anime", anime.getId(), anime.getImageUrl());
		
		if(anime.getRelations() != null && anime.getRelations().size() != 0) {
			for(Related r : anime.getRelations()) {
				ContentValues contentValuesRelated = new ContentValues();
				
				contentValuesRelated.put(RelatedColumn.IS_ANIME, r.isAnime());
				contentValuesRelated.put(RelatedColumn.MASTER_ID, r.getMasterId());
				contentValuesRelated.put(RelatedColumn.RELATED_ID, r.getRelatedId());
				contentValuesRelated.put(RelatedColumn.TITLE, r.getTitle());
				contentValuesRelated.put(RelatedColumn.TYPE, r.getType());
				
				context.getContentResolver().insert(dbUriRelated, contentValuesRelated);
			}
		}
	}
	
	public void updateMangaSync(Manga manga) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(MangaColumn.ALTERNATIVE_VERSION, manga.getAlternative());
		contentValues.put(MangaColumn.ANIME_ADAPTATION, manga.getAnimeAdaptation());
		contentValues.put(MangaColumn.CHAPTERS, manga.getChapters());
		contentValues.put(MangaColumn.ENGLISH, manga.getEnglish());
		contentValues.put(MangaColumn.FAVORITE_COUNT, manga.getFavoriteCount());
		contentValues.put(MangaColumn.GENRES, manga.getGenres());
		contentValues.put(MangaColumn.IMAGE_URL, manga.getImageUrl());
		contentValues.put(MangaColumn.JAPANESE, manga.getJapanese());
		contentValues.put(MangaColumn.LISTED_MANGA, manga.getListedMangaId());
		contentValues.put(MangaColumn.MEMBER_COUNT, manga.getMemberCount());
		contentValues.put(MangaColumn.MEMBER_SCORE, manga.getMemberScore());
		contentValues.put(MangaColumn.POPULARITY_RANK, manga.getPopularityRank());
		contentValues.put(MangaColumn.RANK, manga.getRank());
		contentValues.put(MangaColumn.RELATED_MANGA, manga.getRelatedManga());
		contentValues.put(MangaColumn.STATUS, manga.getStatus());
		contentValues.put(MangaColumn.STATUS_SYNC, "sync");
		contentValues.put(MangaColumn.SYNONYM, manga.getSynonyms());
		contentValues.put(MangaColumn.SYNOPSIS, manga.getSynopsis());
		contentValues.put(MangaColumn.TAGS, manga.getTags());
		contentValues.put(MangaColumn.TYPE, manga.getType());
		contentValues.put(MangaColumn.STATUS_SYNC, "sync");
		
		context.getContentResolver().update(dbUriManga, contentValues, MangaColumn.ID + " = ?", new String[] {manga.getId()});
		
		saveCache("manga", manga.getId(), manga.getImageUrl());
		
		if(manga.getRelated() != null && manga.getRelated().size() != 0) {
			for(Related r : manga.getRelated()) {
				ContentValues contentValuesRelated = new ContentValues();
				
				contentValuesRelated.put(RelatedColumn.IS_ANIME, r.isAnime());
				contentValuesRelated.put(RelatedColumn.MASTER_ID, r.getMasterId());
				contentValuesRelated.put(RelatedColumn.RELATED_ID, r.getRelatedId());
				contentValuesRelated.put(RelatedColumn.TITLE, r.getTitle());
				contentValuesRelated.put(RelatedColumn.TYPE, r.getType());
				
				context.getContentResolver().insert(dbUriRelated, contentValuesRelated);
			}
		}
		
	}
	
	public void saveImageManga(String id, String imageUrl) {
		saveCache("manga", id, imageUrl);
	}
	
	public void saveAnime(Anime anime) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(AnimeColumn.ID, anime.getId());
		contentValues.put(AnimeColumn.TITLE, anime.getTitle() == null ? "" : anime.getTitle());
		contentValues.put(AnimeColumn.ENGLISH, anime.getEnglish() == null ? "" : anime.getEnglish());
		contentValues.put(AnimeColumn.JAPANESE, anime.getJapanese() == null ? "" : anime.getJapanese());
		contentValues.put(AnimeColumn.SYNONYMS, anime.getSynonyms() == null ? "" : anime.getSynonyms());
		
		contentValues.put(AnimeColumn.SYSNOPSIS, anime.getSynopsis() == null ? "" : anime.getSynopsis());
		contentValues.put(AnimeColumn.TYPE, anime.getType() == null ? "" : anime.getType());
		contentValues.put(AnimeColumn.RANK, anime.getRank() == null ? "" : anime.getRank());
		contentValues.put(AnimeColumn.POPULARITY_RANK, anime.getPopularityRank() == null ? "" : anime.getPopularityRank());
		contentValues.put(AnimeColumn.IMAGE_URL, anime.getImageUrl() == null ? "" : anime.getImageUrl());
		
		contentValues.put(AnimeColumn.EPISODE, anime.getEpisode() == null ? "" : anime.getEpisode());
		contentValues.put(AnimeColumn.STATUS, anime.getStatus() == null ? "" : anime.getStatus());
		contentValues.put(AnimeColumn.START_DATE, anime.getStartDate() == null ? "" : anime.getStartDate());
		contentValues.put(AnimeColumn.END_DATE, anime.getEndDate() == null ? "" : anime.getEndDate());
		contentValues.put(AnimeColumn.GENRE, anime.getGenre() == null ? "" : anime.getGenre());
		
		contentValues.put(AnimeColumn.TAGS, anime.getTags() == null ? "" : anime.getTags());
		contentValues.put(AnimeColumn.CLASSIFICATION, anime.getClassification() == null ? "" : anime.getClassification());
		contentValues.put(AnimeColumn.MEMBER_SCORE, anime.getMemberScore() == null ? "" : anime.getMemberScore());
		contentValues.put(AnimeColumn.MEMBER_COUNT, anime.getMemberCount() == null ? "" : anime.getMemberCount());
		contentValues.put(AnimeColumn.FAVORITE_COUNT, anime.getFavoriteCount() == null ? "" : anime.getFavoriteCount());
		
		contentValues.put(AnimeColumn.PARENT_STORY, anime.getParentStory() == null ? "" : anime.getParentStory());
		contentValues.put(AnimeColumn.LISTED_ANIME_ID, anime.getListedAnimeId() == null ? "" : anime.getListedAnimeId());
		contentValues.put(AnimeColumn.WATCHED_EPISODE, anime.getWatchedEpisode() == null ? "" : anime.getWatchedEpisode());
		contentValues.put(AnimeColumn.SCORE, anime.getScore() == null ? "" : anime.getScore());
		contentValues.put(AnimeColumn.WATCHED_STATUS, anime.getWathcedStatus() == null ? "" : anime.getWathcedStatus());
		contentValues.put(AnimeColumn.ADAPTATION, anime.getAdaptation() == null ? "" : anime.getAdaptation());
		contentValues.put(AnimeColumn.SIDE_STORY, anime.getSideStory() == null ? "" : anime.getSideStory());
		contentValues.put(AnimeColumn.PREQUEL, anime.getPrequel() == null ? "" : anime.getPrequel());
		contentValues.put(AnimeColumn.SEQUEL, anime.getSequel() == null ? "" : anime.getSequel());
		contentValues.put(AnimeColumn.ALTERNATIVE, anime.getAlternative() == null ? "" : anime.getAlternative());
		
		contentValues.put(AnimeColumn.SPIN_OFF, anime.getSpinOff() == null ? "" : anime.getSpinOff());
		contentValues.put(AnimeColumn.COMMENTS, anime.getComments() == null ? "" : anime.getComments());
		contentValues.put(AnimeColumn.PRIORITY, anime.getPriority() == null ? "0" : anime.getPriority());
		contentValues.put(AnimeColumn.STATUS_SYNC, "not sync");

		context.getContentResolver().insert(dbUriAnime, contentValues);
	}

	public void saveManga(Manga manga) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(MangaColumn.ID, manga.getId());
		contentValues.put(MangaColumn.TITLE, manga.getTitle() == null ? "" : manga.getTitle());
		contentValues.put(MangaColumn.RANK, manga.getRank() == null ? "" : manga.getRank());
		contentValues.put(MangaColumn.IMAGE_URL, manga.getImageUrl() == null ? "" : manga.getImageUrl());
		contentValues.put(MangaColumn.TYPE, manga.getType() == null ? "" : manga.getType());
		contentValues.put(MangaColumn.STATUS, manga.getStatus() == null ? "" : manga.getStatus());
		contentValues.put(MangaColumn.VOLUMES, manga.getVolumes() == null ? "" : manga.getVolumes());
		contentValues.put(MangaColumn.CHAPTERS, manga.getChapters() == null ? "" : manga.getChapters());
		contentValues.put(MangaColumn.GENRES, manga.getGenres() == null ? "" : manga.getGenres());
		contentValues.put(MangaColumn.MEMBER_SCORE, manga.getMemberScore() == null ? "" : manga.getMemberScore());
		contentValues.put(MangaColumn.MEMBER_COUNT, manga.getMemberCount() == null ? "" : manga.getMemberCount());
		contentValues.put(MangaColumn.POPULARITY_RANK, manga.getPopularityRank() == null ? "" : manga.getPopularityRank());
		contentValues.put(MangaColumn.FAVORITE_COUNT, manga.getFavoriteCount() == null ? "" : manga.getFavoriteCount());
		contentValues.put(MangaColumn.TAGS, manga.getTags() == null ? "" : manga.getTags());
		contentValues.put(MangaColumn.SYNOPSIS, manga.getSynopsis() == null ? "" : manga.getSynopsis());
		contentValues.put(MangaColumn.READ_STATUS, manga.getReadStatus() == null ? "" : manga.getReadStatus());
		contentValues.put(MangaColumn.LISTED_MANGA, manga.getListedMangaId() == null ? "" : manga.getListedMangaId());
		contentValues.put(MangaColumn.CHAPTER_READ, manga.getChapterRead() == null ? "" : manga.getChapterRead());
		contentValues.put(MangaColumn.VOLUME_READ, manga.getVolumesRead() == null ? "" : manga.getVolumesRead());
		contentValues.put(MangaColumn.SCORE, manga.getScore() == null ? "" : manga.getScore());
		contentValues.put(MangaColumn.PRIORITY, manga.getPriority() == null ? "0" : manga.getPriority());
		contentValues.put(MangaColumn.STATUS_SYNC, "not sync");

		context.getContentResolver().insert(dbUriManga, contentValues);
	}

	public List<Anime> getAnimeOverall(String status, int sort) {
		Log.d("Database", sort + " asdas");
		Cursor cursor = context.getContentResolver().query(dbUriAnime, null,
				AnimeColumn.WATCHED_STATUS + " = ?", new String[] { status },
				sort == 1 ? AnimeColumn.TITLE + " ASC" : AnimeColumn.PRIORITY + " DESC");
		
		List<Anime> animes = new ArrayList<Anime>();
		if(cursor != null) {
			while(cursor.moveToNext()) {
				Anime anime = new Anime();
				
				anime.setAdaptation(cursor.getString(cursor.getColumnIndex(AnimeColumn.ADAPTATION)));
				anime.setAlternative(cursor.getString(cursor.getColumnIndex(AnimeColumn.ALTERNATIVE)));
				anime.setClassification(cursor.getString(cursor.getColumnIndex(AnimeColumn.CLASSIFICATION)));
				anime.setComments(cursor.getString(cursor.getColumnIndex(AnimeColumn.COMMENTS)));
				anime.setEndDate(cursor.getString(cursor.getColumnIndex(AnimeColumn.END_DATE)));
				anime.setEnglish(cursor.getString(cursor.getColumnIndex(AnimeColumn.ENGLISH)));
				anime.setEpisode(cursor.getString(cursor.getColumnIndex(AnimeColumn.EPISODE)));
				anime.setFavoriteCount(cursor.getString(cursor.getColumnIndex(AnimeColumn.FAVORITE_COUNT)));
				anime.setGenre(cursor.getString(cursor.getColumnIndex(AnimeColumn.GENRE)));
				anime.setId(cursor.getString(cursor.getColumnIndex(AnimeColumn.ID)));
				
				anime.setImageUrl(cursor.getString(cursor.getColumnIndex(AnimeColumn.IMAGE_URL)));
				anime.setJapanese(cursor.getString(cursor.getColumnIndex(AnimeColumn.JAPANESE)));
				anime.setListedAnimeId(cursor.getString(cursor.getColumnIndex(AnimeColumn.LISTED_ANIME_ID)));
				anime.setMemberCount(cursor.getString(cursor.getColumnIndex(AnimeColumn.MEMBER_COUNT)));
				anime.setMemberScore(cursor.getString(cursor.getColumnIndex(AnimeColumn.MEMBER_SCORE)));
				anime.setParentStory(cursor.getString(cursor.getColumnIndex(AnimeColumn.PARENT_STORY)));
				anime.setPopularityRank(cursor.getString(cursor.getColumnIndex(AnimeColumn.POPULARITY_RANK)));
				anime.setPrequel(cursor.getString(cursor.getColumnIndex(AnimeColumn.PREQUEL)));
				anime.setRank(cursor.getString(cursor.getColumnIndex(AnimeColumn.RANK)));
				anime.setScore(cursor.getString(cursor.getColumnIndex(AnimeColumn.SCORE)));
				
				anime.setSequel(cursor.getString(cursor.getColumnIndex(AnimeColumn.SEQUEL)));
				anime.setSideStory(cursor.getString(cursor.getColumnIndex(AnimeColumn.SIDE_STORY)));
				anime.setSpinOff(cursor.getString(cursor.getColumnIndex(AnimeColumn.SPIN_OFF)));
				anime.setStartDate(cursor.getString(cursor.getColumnIndex(AnimeColumn.START_DATE)));
				anime.setStatus(cursor.getString(cursor.getColumnIndex(AnimeColumn.STATUS)));
				anime.setSynonyms(cursor.getString(cursor.getColumnIndex(AnimeColumn.SYNONYMS)));
				anime.setSynopsis(cursor.getString(cursor.getColumnIndex(AnimeColumn.SYSNOPSIS)));
				anime.setTags(cursor.getString(cursor.getColumnIndex(AnimeColumn.TAGS)));
				anime.setTitle(cursor.getString(cursor.getColumnIndex(AnimeColumn.TITLE)));
				anime.setType(cursor.getString(cursor.getColumnIndex(AnimeColumn.TYPE)));
				anime.setPriority(cursor.getString(cursor.getColumnIndex(AnimeColumn.PRIORITY)));
				
				anime.setWatchedEpisode(cursor.getString(cursor.getColumnIndex(AnimeColumn.WATCHED_EPISODE)));
				anime.setWathcedStatus(cursor.getString(cursor.getColumnIndex(AnimeColumn.WATCHED_STATUS)));
				
				animes.add(anime);
			}
		}
		
		cursor.close();
		
		return animes;
	}
	
	public List<Manga> getMangaOverall(String status) {
		Cursor cursor = context.getContentResolver().query(dbUriManga, null,
				MangaColumn.READ_STATUS + " = ?", new String[] { status },
				MangaColumn.TITLE + " ASC");
		
		List<Manga> mangas = new ArrayList<Manga>();
		if(cursor != null) {
			while(cursor.moveToNext()) {
				Manga manga = new Manga();
				
				manga.setChapterRead(cursor.getString(cursor.getColumnIndex(MangaColumn.CHAPTER_READ)));
				manga.setChapters(cursor.getString(cursor.getColumnIndex(MangaColumn.CHAPTERS)));
				manga.setFavoriteCount(cursor.getString(cursor.getColumnIndex(MangaColumn.FAVORITE_COUNT)));
				manga.setGenres(cursor.getString(cursor.getColumnIndex(MangaColumn.GENRES)));
				manga.setId(cursor.getString(cursor.getColumnIndex(MangaColumn.ID)));
				manga.setImageUrl(cursor.getString(cursor.getColumnIndex(MangaColumn.IMAGE_URL)));
				manga.setListedMangaId(cursor.getString(cursor.getColumnIndex(MangaColumn.LISTED_MANGA)));
				manga.setMemberCount(cursor.getString(cursor.getColumnIndex(MangaColumn.MEMBER_COUNT)));
				manga.setMemberScore(cursor.getString(cursor.getColumnIndex(MangaColumn.MEMBER_SCORE)));
				manga.setPopularityRank(cursor.getString(cursor.getColumnIndex(MangaColumn.POPULARITY_RANK)));
				manga.setRank(cursor.getString(cursor.getColumnIndex(MangaColumn.RANK)));
				manga.setReadStatus(cursor.getString(cursor.getColumnIndex(MangaColumn.READ_STATUS)));
				manga.setScore(cursor.getString(cursor.getColumnIndex(MangaColumn.SCORE)));
				manga.setStatus(cursor.getString(cursor.getColumnIndex(MangaColumn.STATUS)));
				manga.setSynopsis(cursor.getString(cursor.getColumnIndex(MangaColumn.SYNOPSIS)));
				manga.setTags(cursor.getString(cursor.getColumnIndex(MangaColumn.TAGS)));
				manga.setTitle(cursor.getString(cursor.getColumnIndex(MangaColumn.TITLE)));
				manga.setType(cursor.getString(cursor.getColumnIndex(MangaColumn.TYPE)));
				manga.setVolumes(cursor.getString(cursor.getColumnIndex(MangaColumn.VOLUMES)));
				manga.setVolumesRead(cursor.getString(cursor.getColumnIndex(MangaColumn.VOLUME_READ)));
				manga.setPriority(cursor.getString(cursor.getColumnIndex(MangaColumn.PRIORITY)));
				
				mangas.add(manga);
			}
		}
		
		cursor.close();
		
		return mangas;
	}
	
	public void updateAnime(Anime anime) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(AnimeColumn.START_DATE, anime.getStartDate());
		contentValues.put(AnimeColumn.END_DATE, anime.getEndDate());
		contentValues.put(AnimeColumn.TAGS, anime.getTags());
		contentValues.put(AnimeColumn.WATCHED_EPISODE, anime.getWatchedEpisode());
		contentValues.put(AnimeColumn.WATCHED_STATUS, anime.getWathcedStatus());
		contentValues.put(AnimeColumn.COMMENTS, anime.getComments());
		contentValues.put(AnimeColumn.SCORE, anime.getScore());
		
		context.getContentResolver().update(dbUriAnime, contentValues, AnimeColumn.ID + " = ?", new String[] {anime.getId()});
	}
	
	public void updateAnimeWithPriority(Anime anime) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(AnimeColumn.START_DATE, anime.getStartDate());
		contentValues.put(AnimeColumn.END_DATE, anime.getEndDate());
		contentValues.put(AnimeColumn.TAGS, anime.getTags());
		contentValues.put(AnimeColumn.WATCHED_EPISODE, anime.getWatchedEpisode());
		contentValues.put(AnimeColumn.WATCHED_STATUS, anime.getWathcedStatus());
		contentValues.put(AnimeColumn.COMMENTS, anime.getComments());
		contentValues.put(AnimeColumn.SCORE, anime.getScore());
		contentValues.put(AnimeColumn.PRIORITY, anime.getPriority());
		
		context.getContentResolver().update(dbUriAnime, contentValues, AnimeColumn.ID + " = ?", new String[] {anime.getId()});
	}
	
	public void updateManga(Manga manga) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(MangaColumn.READ_STATUS, manga.getReadStatus());
		contentValues.put(MangaColumn.CHAPTER_READ, manga.getChapterRead());
		contentValues.put(MangaColumn.VOLUME_READ, manga.getVolumesRead());
		contentValues.put(MangaColumn.SCORE, manga.getScore());
		contentValues.put(MangaColumn.START_DATE, manga.getStartDate());
		contentValues.put(MangaColumn.END_DATE, manga.getEndDate());
		contentValues.put(MangaColumn.TAGS, manga.getTags());
		contentValues.put(MangaColumn.COMMENTS, manga.getComments());
		
		context.getContentResolver().update(dbUriManga, contentValues, MangaColumn.ID + " = ?", new String[] {manga.getId()});
	}
	
	public void updateMangaWithPriority(Manga manga) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(MangaColumn.READ_STATUS, manga.getReadStatus());
		contentValues.put(MangaColumn.CHAPTER_READ, manga.getChapterRead());
		contentValues.put(MangaColumn.VOLUME_READ, manga.getVolumesRead());
		contentValues.put(MangaColumn.SCORE, manga.getScore());
		contentValues.put(MangaColumn.START_DATE, manga.getStartDate());
		contentValues.put(MangaColumn.END_DATE, manga.getEndDate());
		contentValues.put(MangaColumn.TAGS, manga.getTags());
		contentValues.put(MangaColumn.COMMENTS, manga.getComments());
		contentValues.put(MangaColumn.PRIORITY, manga.getPriority());
		
		context.getContentResolver().update(dbUriManga, contentValues, MangaColumn.ID + " = ?", new String[] {manga.getId()});
	}
	
//	public void updateManualAnime(Anime anime) {
//		ContentValues contentValues = new ContentValues();
//		contentValues.put(AnimeColumn.WATCHED_EPISODE, anime.getWatchedEpisode());
//		contentValues.put(AnimeColumn.WATCHED_STATUS, anime.getWathcedStatus());
//		contentValues.put(AnimeColumn.SCORE, anime.getScore());
//		
//		context.getContentResolver().update(dbUriAnime, contentValues, AnimeColumn.ID + " = ?", new String[] {anime.getId()});
//	}
	
//	public void updateManualManga(Manga manga) {
//		ContentValues contentValues = new ContentValues();
//		contentValues.put(MangaColumn.CHAPTER_READ, manga.getChapterRead());
//		contentValues.put(MangaColumn.VOLUME_READ, manga.getVolumesRead());
//		contentValues.put(MangaColumn.READ_STATUS, manga.getReadStatus());
//		contentValues.put(MangaColumn.SCORE, manga.getScore());
//		
//		context.getContentResolver().update(dbUriManga, contentValues, MangaColumn.ID + " = ?", new String[] {manga.getId()});
//	}
	
	public void insertHistory(History history, String imageUrl) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(HistoryColumn.TITLE, history.getTitle());
		contentValues.put(HistoryColumn.DESCRIPTION, history.getDescription());
		contentValues.put(HistoryColumn.UPDATE_DATE, history.getUpdateDate());
		contentValues.put(HistoryColumn.TYPE, history.getType());
		contentValues.put(HistoryColumn.ANIME_ID, history.getAnimeId());
		contentValues.put(HistoryColumn.MANGA_ID, history.getMangaId());
		
		context.getContentResolver().insert(dbUriHistory, contentValues);
		
//		File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), ConnectionUtil.CACHE_PATH);
//		if (!mediaStorageDir.exists()) {
//			if (!mediaStorageDir.mkdirs()) {
//				Log.d("Folder", "failed to create directory");
//			}
//		}
//		
//		String path = "";
		if(history.getAnimeId().length() != 0) {
//			path = mediaStorageDir.getPath() + File.separator + "anime_" + history.getAnimeId();
			saveCache("anime", history.getAnimeId(), imageUrl);
		} else {
//			path = mediaStorageDir.getPath() + File.separator + "manga_" + history.getMangaId();
			saveCache("manga", history.getMangaId(), imageUrl);
		}
//		
//		File mediaFile = new File(path);
//		
//		try {
//			URL url = new URL(imageUrl);
//			Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
//			bitmap.compress(CompressFormat.PNG, 100, new FileOutputStream(mediaFile));
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}
	
	public boolean hasHistory(History history) {
		Cursor cursor = context.getContentResolver().query(dbUriHistory, null,
				HistoryColumn.MANGA_ID + " = ? AND " + HistoryColumn.ANIME_ID + " = ? AND " + HistoryColumn.TYPE + " = ?", 
				new String[] { history.getMangaId(), history.getAnimeId(), history.getType()}, null);
		
		boolean check = false;
		
		if(cursor != null) {
			if(cursor.getCount() > 0) {
				check = true;
			} else {
				check = false;
			}
		}
		
		return check;
	}
	
	public void updateHistory(History history) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(HistoryColumn.TITLE, history.getTitle());
		contentValues.put(HistoryColumn.DESCRIPTION, history.getDescription());
		contentValues.put(HistoryColumn.UPDATE_DATE, history.getUpdateDate());
		contentValues.put(HistoryColumn.TYPE, history.getType());
		contentValues.put(HistoryColumn.ANIME_ID, history.getAnimeId());
		contentValues.put(HistoryColumn.MANGA_ID, history.getMangaId());
		
		context.getContentResolver().update(dbUriHistory, contentValues, 
				HistoryColumn.MANGA_ID + " = ? AND " + HistoryColumn.ANIME_ID + " = ? AND " + HistoryColumn.TYPE + " = ?", 
				new String[] { history.getMangaId(), history.getAnimeId(), history.getType()});
	}
	
	public void deleteHistory() {
		context.getContentResolver().delete(dbUriHistory, null, null);
	}
	
	public List<History> getHistory(String type) {
		List<History> histories = new ArrayList<History>();
		Cursor cursor = context.getContentResolver().query(dbUriHistory, null, HistoryColumn.TYPE + " = ?", new String[] { type }, HistoryColumn.UPDATE_DATE + " DESC");
		int a = 1;
		if(cursor != null) {
			while(cursor.moveToNext()) {
				if(a <= 3) {
					History history = new History();
					
					history.setAnimeId(cursor.getString(cursor.getColumnIndex(HistoryColumn.ANIME_ID)));
					history.setDescription(cursor.getString(cursor.getColumnIndex(HistoryColumn.DESCRIPTION)));
					history.setMangaId(cursor.getString(cursor.getColumnIndex(HistoryColumn.MANGA_ID)));
					history.setTitle(cursor.getString(cursor.getColumnIndex(HistoryColumn.TITLE)));
					history.setType(cursor.getString(cursor.getColumnIndex(HistoryColumn.TYPE)));
					history.setUpdateDate(cursor.getString(cursor.getColumnIndex(HistoryColumn.UPDATE_DATE)));
					
					histories.add(history);
					
					a++;
				}
			}
		}
		cursor.close();
		
		return histories;
	}
	
	private void saveCache(String type, String id, String imageUrl) {
		String state = Environment.getExternalStorageState();
		File mediaStorageDir = null;
		
		
		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    mediaStorageDir = new File(context.getExternalCacheDir(), "");
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			mediaStorageDir = new File(context.getCacheDir(), "");
		} else {
		    mediaStorageDir = new File(context.getCacheDir(), "");
		}
		
		
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("Folder", "failed to create directory");
			}
		}
		
		File mediaFile = new File(mediaStorageDir.getPath() + File.separator + type + "_" + id);
		
		try {
			URL url = new URL(imageUrl);
			Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
			bitmap.compress(CompressFormat.PNG, 100, new FileOutputStream(mediaFile));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
